package com.nowcoder.community.controller;

import com.alibaba.fastjson.JSONObject;
import com.nowcoder.community.pojo.Message;
import com.nowcoder.community.pojo.Page;
import com.nowcoder.community.pojo.User;
import com.nowcoder.community.service.CommentService;
import com.nowcoder.community.service.MessageService;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.CommunityUtil;
import com.nowcoder.community.util.HostHolder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.HtmlUtils;

import java.util.*;

@Api(description = "消息（包括私信和通知）相关")
@Controller
public class MessageController implements CommunityConstant{

    @Autowired
    @Qualifier("messageService")
    private MessageService messageService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    @Qualifier("userService")
    private UserService userService;

    @Autowired
    @Qualifier("commentService")
    private CommentService commentService;

    @ApiOperation(value = "获取私信列表")
    @GetMapping("/letter/list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "分页实例")
    })
    public String getLetterList(Model model, Page page){

        //获取当前用户
        User user = hostHolder.getUser();

        page.setLimit(5);
        page.setPath("/letter/list");
        page.setRows(messageService.statisticsConversationCount(user.getId()));

        //会话列表------------------------------------------------
        List<Message> conversationList = messageService.findConversations(user.getId(),
                page.getOffset(), page.getLimit());

        List<Map<String, Object>> conversations = new ArrayList<>();
        //将每个会话实例、会话中的已读私信数、未读私信数以及目标用户存放到map集合中
        if (conversations != null){
            for (Message message : conversationList) {
                Map<String, Object> map = new HashMap<>();
                map.put("conversation", message);
                map.put("letterCount", messageService.statisticsLetterCount(message.getConversationId()));
                //查询某个会话中未读私信数量
                map.put("unreadCount", messageService.statisticsLetterUnreadCount(user.getId(),
                        message.getConversationId()));

                int targetId = user.getId() == message.getFromId() ? message.getToId() : message.getFromId();

                map.put("target", userService.findUserById(targetId));

//                System.out.println("--->" + targetId);
//                System.out.println("--->" + userService.findUserById(targetId));
                conversations.add(map);
            }
        }
        model.addAttribute("conversations", conversations);

        //查询未读消息总的数量
        int letterUnreadCount = messageService.statisticsLetterUnreadCount(user.getId(), null);
        model.addAttribute("letterUnreadCount", letterUnreadCount);

        //查询未读通知总数量
        int noticeUnreadCount = messageService.findNoticeUnreadCount(user.getId(), null);
        model.addAttribute("noticeUnreadCount", noticeUnreadCount);

        return "site/letter";
    }

    @ApiOperation(value = "获取私信详情")
    @GetMapping("/letter/detail/{conversationId}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "conversationId", value = "会话id"),
            @ApiImplicitParam(name = "page", value = "分页实例")
    })
    public String getLetterDetail(@PathVariable("conversationId") String conversationId, Page page, Model model){
        //分页信息
        page.setLimit(5);
        page.setPath("/letter/detail/" + conversationId);
        page.setRows(messageService.statisticsLetterCount(conversationId));

        //私信列表
        List<Message> letterList = messageService.findLetters(conversationId, page.getOffset(), page.getLimit());

        List<Map<String, Object>> letters = new ArrayList<>();

        if (letterList != null){
            //将私信实例和私信发送用户存放到map集合中
            for (Message message : letterList) {
                Map<String, Object> map = new HashMap<>();
                map.put("letter", message);
                map.put("fromUser", userService.findUserById(message.getFromId()));

                letters.add(map);
            }
        }

        model.addAttribute("letters", letters);

        //私信目标-----------------------------------
        model.addAttribute("target", getLetterTargetUser(conversationId));

        //将未读的私信设置为已读
        List<Integer> ids = getLetterIds(letterList);
        if (!ids.isEmpty() && ids != null){
            messageService.updateMessageStatus(ids);
        }

        return "site/letter-detail";
    }

    private User getLetterTargetUser(String conversationId){
        String[] ids = conversationId.split("_");

        int id0 = Integer.parseInt(ids[0]);
        int id1 = Integer.parseInt(ids[1]);

        if (hostHolder.getUser().getId() == id0){
            return userService.findUserById(id1);
        }else {
            return userService.findUserById(id0);
        }
    }

    //获取私信列表中的私信id
    private List<Integer> getLetterIds(List<Message> letterList){
        List<Integer> ids = new ArrayList<>();

        if (letterList != null){
            for (Message message : letterList) {
                if ((hostHolder.getUser().getId() == message.getToId()) && (message.getStatus() == 0)){
                    ids.add(message.getId());
                }
            }
        }

        return ids;
    }

    @ApiOperation(value = "发送私信")
    @PostMapping("/letter/send")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "toName", value = "私信发起人"),
            @ApiImplicitParam(name = "content", value = "私信内容")
    })
    public String sendLetter(String toName, String content){

        //获取目标用户
        User targetUser = userService.findUserByName(toName);

        if (targetUser == null){
            CommunityUtil.getJSONString(1, "目标用户不存在！");
        }

        Message message = new Message();
        //发送私信的用户id为当前用户id
        message.setFromId(hostHolder.getUser().getId());
        //设置私信的目标用户id
        message.setToId(targetUser.getId());

        if (message.getFromId() < message.getToId()){
            message.setConversationId(message.getFromId() + "_" + message.getToId());
        }else {
            message.setConversationId(message.getToId() + "_" + message.getFromId());
        }

        //设置私信内容
        message.setContent(content);
        //设置私信的创建时间
        message.setCreateTime(new Date());
        //添加私信
        messageService.addMessage(message);

        return CommunityUtil.getJSONString(0);
    }


    @ApiOperation(value = "获取私信列表")
    @GetMapping("/notice/list")
    public String getNoticeList(Model model){

        User user = hostHolder.getUser();

        //查询最新的评论类通知
        Message message = messageService.findLatestNotice(user.getId(), TOPIC_COMMENT);
        //将评论的相关信息存放到容器中
        Map<String, Object> messageVo = new HashMap<>();

        if (message != null){
            messageVo.put("message", message);

            String content = HtmlUtils.htmlUnescape(message.getContent());

            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);

            messageVo.put("user", userService.findUserById((Integer) data.get("userId")));
            messageVo.put("entityType", data.get("entityType"));
            messageVo.put("entityId", data.get("entityId"));
            messageVo.put("discussPostId", data.get("discussPostId"));

            int commentNoticeCount = messageService.findNoticeCount(user.getId(), TOPIC_COMMENT);
            messageVo.put("count", commentNoticeCount);

            int unreadCount = messageService.findNoticeUnreadCount(user.getId(), TOPIC_COMMENT);
            messageVo.put("unread", unreadCount);
        }
        model.addAttribute("commentNotice", messageVo.isEmpty() ? null : messageVo);

        //查询最新的点赞类通知
        message = messageService.findLatestNotice(user.getId(), TOPIC_LIKE);
        //将点赞的相关信息存放到容器中
        messageVo = new HashMap<>();

        if (message != null){
            messageVo.put("message", message);

            String content = HtmlUtils.htmlUnescape(message.getContent());

            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);

            messageVo.put("user", userService.findUserById((Integer) data.get("userId")));
            messageVo.put("entityType", data.get("entityType"));
            messageVo.put("entityId", data.get("entityId"));
            messageVo.put("discussPostId", data.get("discussPostId"));

            int likeNoticeCount = messageService.findNoticeCount(user.getId(), TOPIC_LIKE);
            messageVo.put("count", likeNoticeCount);

            int unreadCount = messageService.findNoticeUnreadCount(user.getId(), TOPIC_LIKE);
            messageVo.put("unread", unreadCount);
        }
        model.addAttribute("likeNotice", messageVo.isEmpty() ? null : messageVo);

        //查询最新的关注类通知
        message = messageService.findLatestNotice(user.getId(), TOPIC_FOLLOW);
        //将关注的相关信息存放到容器中
        messageVo = new HashMap<>();

        if (message != null){
            messageVo.put("message", message);

            String content = HtmlUtils.htmlUnescape(message.getContent());

            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);

            messageVo.put("user", userService.findUserById((Integer) data.get("userId")));
            messageVo.put("entityType", data.get("entityType"));
            messageVo.put("entityId", data.get("entityId"));

            int followNoticeCount = messageService.findNoticeCount(user.getId(), TOPIC_FOLLOW);
            messageVo.put("count", followNoticeCount);

            int unreadCount = messageService.findNoticeUnreadCount(user.getId(), TOPIC_FOLLOW);
            messageVo.put("unread", unreadCount);
        }
        model.addAttribute("followNotice", messageVo.isEmpty() ? null : messageVo);

        //查询未读私信数量
        int letterUnreadCount = messageService.statisticsLetterUnreadCount(user.getId(), null);
        model.addAttribute("letterUnreadCount", letterUnreadCount);

        //查询未读通知总数量
        int noticeUnreadCount = messageService.findNoticeUnreadCount(user.getId(), null);
        model.addAttribute("noticeUnreadCount", noticeUnreadCount);

        return "site/notice";
    }

    @ApiOperation(value = "获取通知详情")
    @GetMapping("/notice/detail/{topic}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "topic", value = "主题类型（点赞、关注或评论）")
    })
    public String getNoticeDetail(@PathVariable("topic") String topic, Page page, Model model){

        User user = hostHolder.getUser();

        page.setLimit(5);
        page.setPath("/notice/detail/" + topic);
        page.setRows(messageService.findNoticeCount(user.getId(), topic));

        //查询每一页的通知列表（任意时刻的）
        List<Message> noticeList = messageService.findNotices(user.getId(), topic, page.getOffset(), page.getLimit());

        List<Map<String, Object>> noticeVoList = new ArrayList<>();

        if (noticeList != null){
            for (Message notice : noticeList) {
                Map<String, Object> map = new HashMap<>();

                //通知
                map.put("notice", notice);

                //内容
                String content = HtmlUtils.htmlUnescape(notice.getContent());

                Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);

                map.put("user", userService.findUserById((Integer) data.get("userId")));
                map.put("entityType", data.get("entityType"));
                map.put("entityId", data.get("entityId"));
                map.put("discussPostId", data.get("discussPostId"));
                //通知作者
                map.put("fromUser", userService.findUserById(notice.getFromId()));

                noticeVoList.add(map);
            }
        }

        model.addAttribute("notices", noticeVoList);



        //设置已读
        List<Integer> ids = getLetterIds(noticeList);
        if (!ids.isEmpty()){
            messageService.updateMessageStatus(ids);
        }

        return "site/notice-detail";
    }
}
